/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.doc.sender.ui;

import com.database.entity.MenuPrivs;
import database.senderUtil;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.lang.Object;
import java.util.List;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author parent
 */
public class PrivilegeFrame extends javax.swing.JFrame {
private boolean DEBUG = false;
    /**
     * Creates new form PrivilegeFrame
     */
    public PrivilegeFrame() {
        initComponents();
        PopulateToList populate=new PopulateToList();
        cbGroups.setModel(populate.GetGroupComboModel());
        //DefaultTableModel model=populate.GetPrivilegesTableModel(1);
//        if (model!=null){
//            tblPrivs.setModel(model);
//        }
        GetPrivilegesTableModel(tblPrivs, 1);
    }
   public class CustomTableCellRenderer extends DefaultTableCellRenderer {
        public Component getTableCellRendererComponent (JTable table, 
            Object obj, boolean isSelected, boolean hasFocus, 
            int row, int column) {
        Component cell = super.getTableCellRendererComponent(
        table, obj, isSelected, hasFocus, row, column);
        if (isSelected) {
            cell.setBackground(Color.green);
        } 
        else {
        if (row % 2 == 0) {
            cell.setBackground(Color.cyan);
        }
        else {
            cell.setBackground(Color.lightGray);
        }
        }
   return cell;
  }
  }
 
  class MyCheckBoxRenderer extends JCheckBox implements TableCellRenderer {
  public MyCheckBoxRenderer() {
    setHorizontalAlignment(JLabel.CENTER);
  }

  public Component getTableCellRendererComponent(JTable table, Object value, 
          boolean isSelected,
      boolean hasFocus, int row, int column) {
    if (isSelected) {
      setForeground(table.getSelectionForeground());
      super.setBackground(table.getSelectionBackground());
    } else {
      setForeground(table.getForeground());
      setBackground(table.getBackground());
    }
    
         
        setSelected((value != null && ((Boolean) value).booleanValue()));
    
   return this;
  }
}

public class MyCheckBoxEditor extends DefaultCellEditor implements ItemListener {
    JCheckBox checkBox = new JCheckBox();  
    public MyCheckBoxEditor(JCheckBox cb) {
        super(cb);
        checkBox=cb;
        checkBox.setHorizontalAlignment(SwingConstants.CENTER);  
        checkBox.setBackground(Color.white);  
    }
    public Component getTableCellEditorComponent(JTable table, Object value,  
            boolean isSelected, int row, int column) {  
//        Component cell = super.getTableCellEditorComponent(
//                table, value, isSelected, row, column);
        if (value == null)  
            return checkBox;  
        checkBox.addItemListener(this);  
        if (((Boolean) value).booleanValue())  
            checkBox.setSelected(true);  
        else  
            checkBox.setSelected(false);  
       if (row % 2 == 0) {
            checkBox.setBackground(Color.cyan);
        }
        else {
            checkBox.setBackground(Color.lightGray);
        }
        return checkBox;  
    }  
  
    public Object getCellEditorValue() {  
        if(checkBox.isSelected() == true)  
            return new Boolean(true);  
        else   
            return new Boolean(false);  
    }
        @Override
        public void itemStateChanged(ItemEvent e) {
            
            //System.out.println("Firing!");
         //   throw new UnsupportedOperationException("Not supported yet.");
        }
    }  
   public void GetPrivilegesTableModel(JTable table,int groupid){
       Session session = senderUtil.getSessionFactory().openSession();
        Transaction transaction = null;
        try {
            transaction = session.beginTransaction();
            String queryString = "select privs from MenuPrivs privs "+
            "inner join privs.userGroups as groups,privs.Menus as menu "+
            " where groups.id=:group "
            + " order by privs.id";
            Query query = session.createQuery(queryString);
            query.setInteger("group", groupid);
            List Resulset=query.list();
//            Iterator iters=query.list().iterator();
//            DefaultTableModel model=new DefaultTableModel();
            if (Resulset!=null){
                    Vector<String> tableHeaders = new Vector<String>();
                    Vector tableData = new Vector();
                    tableHeaders.add("Id"); 
                    tableHeaders.add("Menu Caption");
                    tableHeaders.add("Read");
                    tableHeaders.add("Write");
                    tableHeaders.add("Delete");
                    tableHeaders.add("Print");
//                JCheckBox[][] granted=new JCheckBox[50][4];
                int i=0;
                for(Object o:Resulset) {
                    Vector<Object> oneRow = new Vector<Object>();
                    MenuPrivs privs=(MenuPrivs)o;                  
                    oneRow.add(privs.getId());
                    oneRow.add(privs.getMenus().getCaption());
                    
//                    granted[i][0]=new JCheckBox("Grant");
//                    granted[i][0].setSelected(privs.getGrantRead().equals("1"));
//                    oneRow.add(granted[i][0]);
                    oneRow.add(privs.getGrantRead().equals("1"));
                    oneRow.add(privs.getGrantWrite().equals("1"));
                    oneRow.add(privs.getGrantDelete().equals("1"));
                    oneRow.add(privs.getGrantPrint().equals("1"));
                    tableData.add(oneRow);
                    i++;
                    //System.out.println(privs.getMenus().getCaption());
                }
                transaction.commit();
                session.close(); 
                DefaultTableModel  model=new DefaultTableModel(tableData, tableHeaders);
                table.setModel(model);
                TableColumn column=table.getColumnModel().getColumn(2);
                column.setCellRenderer( new MyCheckBoxRenderer());
                column.setCellEditor(new MyCheckBoxEditor(new JCheckBox()));
                column=table.getColumnModel().getColumn(3);
                column.setCellRenderer( new MyCheckBoxRenderer());
                column.setCellEditor(new MyCheckBoxEditor(new JCheckBox()));
                column=table.getColumnModel().getColumn(4);
                column.setCellRenderer( new MyCheckBoxRenderer());
                column.setCellEditor(new MyCheckBoxEditor(new JCheckBox()));
                column=table.getColumnModel().getColumn(5);
                column.setCellRenderer( new MyCheckBoxRenderer());
                column.setCellEditor(new MyCheckBoxEditor(new JCheckBox()));
            }   
               
        } catch (Exception e){
            //return false;
            
        }
   }
   
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSplitPane1 = new javax.swing.JSplitPane();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        cbGroups = new javax.swing.JComboBox();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblPrivs = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        jSplitPane1.setToolTipText("");
        jSplitPane1.setNextFocusableComponent(jPanel2);

        jPanel1.setPreferredSize(new java.awt.Dimension(537, 40));

        jLabel1.setText("Group Name :");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cbGroups, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(309, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(cbGroups, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jSplitPane1.setTopComponent(jPanel1);

        tblPrivs.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null}
            },
            new String [] {
                "Id", "Menu", "Read", "Write", "Delete", "Print"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tblPrivs);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 537, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 344, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );

        jSplitPane1.setRightComponent(jPanel2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 393, Short.MAX_VALUE)
                .addGap(0, 0, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PrivilegeFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(PrivilegeFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(PrivilegeFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PrivilegeFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new PrivilegeFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox cbGroups;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTable tblPrivs;
    // End of variables declaration//GEN-END:variables
}
